<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/5
 * Time: 12:43
 */

namespace app\teacher\controller;


use app\common\model\teacher\Teacher;
use app\common\model\Tag;
use app\teacher\lib\ApiResponse;
use app\teacher\lib\TeacherBaseController;
use http\Exception;
use think\Db;
use think\Request;

class Home extends TeacherBaseController
{
    public function pass(Request $request) {
        if ($request->isPost()) {
            $form = $this->validFormData([
                ['password_old', 'require',],
                ['password_new', 'require',],
            ]);

            if ($form['password_old'] == $form['password_new']) {
                return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'新旧密码相同');
            }

            $teacher = $this->getLogin();
            if ( ! Teacher::passwordVerify($form['password_old'], $teacher->password)) {
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'旧密码错误');
            }

            $teacher->password = Teacher::passwordEncrypt($form['password_new']);
            $teacher->save();

            return ApiResponse::success();
        } else {
            return json([],405);
        }
    }

    public function info(Request $request) {

        if ($request->isPost()) {
            $form = $this->validFormData([
                ['realname', 'require'],
                ['avatar', 'url'],
                ['gender', 'integer|between:1,2'],
                ['success_rate', 'float'],
                ['qualification_certificate', 'url',],
            ]);
            $fields = ['realname','avatar','gender','success_rate','intro','config'];
            $teacher = $this->getLogin();
            foreach ($fields as $field) {
                if (empty($form[$field])) continue;
                $teacher->$field = $form[$field];
            }
            $teacher->save();
            //modify cc 2018-10-10 添加返回值
            $res = [
                'realname'=>$teacher->realname,
                'gender'=>$teacher->gender,
                'config'=>$teacher->config,
                'intro'=>$teacher->intro,
                'avatar'=>$teacher->avatar,
            ];

            return ApiResponse::success($res);
        } else {
            return ApiResponse::success($this->getLogin()->info());
        }

    }


    /**
     * 标签，操作
     *
     * @param Request $request
     * @return ApiResponse
     */
    public function tags(Request $request) {

        if ($request->isGet()) {

            $only_had = $request->param('only_had', false);
            if ($only_had) $list = Tag::getByTeacher($this->teacherId);
            else $list = Tag::all();

            return ApiResponse::success($list);

        } elseif ($request->isPost()) {

            return $this->tagAdd();

        } elseif ($request->isDelete()) {

            return $this->tagRemove();

        } else {
            return response(null, 405);
        }

    }

    private function tagAdd() {

        $form = $this->validFormData([
            ['tag_id', 'integer',],
        ]);

        try{
            Db::startTrans();

            if (empty($form['tag_id']) && empty($form['tag'])) {
                ApiResponse::error(ApiResponse::ERR_FORM_INVALID, '请输入tag或tag_id');
            }

            if (empty($form['tag'])) {
                $tag_id = intval($form['tag_id']);
            } else {
                $data = ['title' => $form['tag']];
                $tag = Tag::get($data);
                if (empty($tag)) {
                    $tag = Tag::create($data);
                }
                $tag_id = $tag->id;
            }
            Tag::addToTeacher($this->teacherId, $tag_id);

            Db::commit();
            return ApiResponse::success([
                'id' => $tag_id,
                'title' => $form['tag'] ?? null,
            ]);

        }catch (Exception $ex){
            Db::rollback();
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $ex->getMessage(), false);
        }
    }

    private function tagRemove() {
        $form = $this->validFormData([
            ['tag_id', 'require|integer',],
        ]);

        Tag::rmFromTeacher($this->teacherId, $form['tag_id']);

        return ApiResponse::success();
    }

}
